# _*_ coding : utf-8 _*_
# @Time : 2025/3/28 23:06
# @Author : 梁满仓
# @File : stock_info
# @Project : stock_of_donnie_day_day_up
import akshare as ak

'''
import pandas as pd
'''


'''
from pathlib import Path

# 获取当前工作目录
current_path = Path.cwd()
print("当前工作目录是:", current_path)
'''


'''
# 获取 A 股所有上市公司的代码和名称
stock_info_a_code_name_df = ak.stock_info_a_code_name()
stock_info_a_code_name_df.to_csv(r'stock_info_a_code_name.csv', index=False)

stock_zh_a_stop_em_df = ak.stock_zh_a_stop_em()
stock_zh_a_stop_em_df.to_csv(r'stock_zh_a_stop_em.csv', index=False)

stock_balance_sheet_by_report_delisted_em_df = ak.stock_balance_sheet_by_report_delisted_em(symbol="SZ000013")
print(stock_balance_sheet_by_report_delisted_em_df)

stock_balance_sheet_by_report_em_df = ak.stock_balance_sheet_by_report_em(symbol="SH600519")
stock_balance_sheet_by_report_em_df.to_csv(r'stock_balance_sheet_by_report_of_600519.csv', index=False)
#print(stock_balance_sheet_by_report_em_df)

#A 股个股指标: 市盈率, 市净率, 股息率
stock_a_indicator_lg_df = ak.stock_a_indicator_lg(symbol="600519")
stock_a_indicator_lg_df.to_csv(r'stock_a_indicator_lg_of_600519.csv', index=False)
#print(stock_a_indicator_lg_df)

#A 股估值指标：百度股市通-A 股-财务报表-估值数据
stock_zh_valuation_baidu_df = ak.stock_zh_valuation_baidu(symbol="600519", indicator="总市值", period="近一年")
stock_zh_valuation_baidu_df.to_csv(r'stock_zh_valuation_baidu_of_600519.csv', index=False)
#print(stock_zh_valuation_baidu_df)

#个股估值：东方财富网-数据中心-估值分析-每日互动-每日互动-估值分析
stock_value_em_df = ak.stock_value_em(symbol="600519")
stock_value_em_df.to_csv(r'stock_value_em_of_600519.csv', index=False)
#print(stock_value_em_df)

#实时行情数据-新浪：新浪财经-沪深京 A 股数据, 重复运行本函数会被新浪暂时封 IP, 建议增加时间间隔
stock_zh_a_spot_df = ak.stock_zh_a_spot()
stock_zh_a_spot_df.to_csv(r'stock_zh_a_spot.csv', index=False)
#print(stock_zh_a_spot_df)

# 获取股票的后复权数据（示例：贵州茅台 "600519"）
stock_code = "600519"
stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol=stock_code, adjust="hfq")  # hfq: 后复权
stock_zh_a_hist_df.to_csv(r'stock_zh_a_hist_of_600519.csv', index=False)

'''

import pandas as pd
import requests
import json
from datetime import datetime, timedelta
import time


def get_sina_data_by_day(target_date):
    """获取指定日期的5分钟数据"""
    url = f"http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sh000300&scale=5&datalen=1000&date={target_date}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
    }

    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        data = json.loads(response.text)

        if not data:
            print(f"{target_date}: 无数据")
            return None

        df = pd.DataFrame(data)
        df['datetime'] = pd.to_datetime(df['day'])
        df['date'] = df['datetime'].dt.date
        df['time'] = df['datetime'].dt.time
        df = df[['date', 'time', 'open', 'high', 'low', 'close', 'volume']].astype({
            'open': float, 'high': float, 'low': float, 'close': float, 'volume': float
        })
        print(f"{target_date}: 获取成功（{len(df)}条）")
        return df

    except Exception as e:
        print(f"{target_date}: 请求失败 - {str(e)}")
        return None


# 获取最近N天的数据（示例：365天）
all_data = []
days_to_fetch = 30

for i in range(days_to_fetch):
    target_date = (datetime.now() - timedelta(days=i)).strftime("%Y-%m-%d")
    daily_data = get_sina_data_by_day(target_date)

    if daily_data is not None:
        all_data.append(daily_data)

    time.sleep(1)  # 避免请求过于频繁

# 合并有效数据
if all_data:
    df = pd.concat(all_data, ignore_index=True)
    df.to_csv("沪深300_5分钟_历史数据.csv", encoding='utf_8_sig', index=False)
    print(f"数据已保存，共{len(df)}条记录")
else:
    print("未获取到任何有效数据，请检查：")
    print("1. 网络连接是否正常")
    print("2. 新浪财经API是否变更")
    print("3. 尝试减少请求天数（days_to_fetch）")